package migrator

import (
	"context"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/config"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/clickhouse"

	"github.com/riete/errors"
)

func GenerateConfig(source *clickhouse.Clickhouse, path string) errors.Error {
	writeConfig := &config.Migration{
		Source:          config.Config.Source,
		MigrationConfig: config.Config.MigrationConfig,
		Target:          config.Config.Target,
		BatchSize:       config.Config.BatchSize,
		Concurrency:     config.Config.Concurrency, // 将QPS改为Concurrency
	}
	rows, err := source.Query(context.Background(), "select `database`,name from `system`.`tables` t where `database` not in ('system','information_schema')  and is_temporary = 0 and `engine` = 'Distributed' order by `database`,name")
	if err != nil {
		return err.Trace("查询数据库db失败")
	}

	dbTableConfig := make(map[string][]config.Table)
	for rows.Next() {
		var result struct {
			Database  string `ch:"database"`
			TableName string `ch:"name"`
		}
		if err := rows.ScanStruct(&result); err != nil {
			return errors.NewFromErr(err)
		}
		if config.Config.Match(result.Database, result.TableName) {
			tables := dbTableConfig[result.Database]
			tables = append(
				tables,
				config.Table{
					Source:      result.TableName,
					Target:      result.TableName,
					Distributed: true,
				},
			)
			dbTableConfig[result.Database] = tables
		}
	}
	for db, tables := range dbTableConfig {
		writeConfig.DatabaseConfig = append(writeConfig.DatabaseConfig, config.Database{
			Source: db,
			Target: db,
			Tables: tables,
		})
	}
	return config.WriteConfig(path, writeConfig)
}